package a08_回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * a20_N皇后
 * </p>
 *
 * @author flyduck
 * @since 2025-01-05
 */
public class a20_N皇后 {
    public static void main(String[] args) {
        a20_N皇后 test = new a20_N皇后();
        List<List<String>> lists = test.solveNQueens(4);
        System.out.println(lists);
    }

    public List<List<String>> solveNQueens(int n) {
        List<List<String>> result = new ArrayList<>();
        char[][] path = new char[n][n];
        for (int i = 0; i < path.length; i++) {
            for (int j = 0; j < path[i].length; j++) {
                path[i][j] = '.';
            }
        }
        traversal(result, path, n, 0);
        return result;
    }

    private void traversal(List<List<String>> result,
                           char[][] path,
                           int n,
                           int rowIdx){
        if (rowIdx == n) {
            result.add(charsToList(path));
        }

        for (int i = 0; i < n; i++) {
            if(!isValid(path,n,rowIdx,i)){
                continue;
            }
            path[rowIdx][i] = 'Q';
            traversal(result, path, n, rowIdx + 1);
            path[rowIdx][i] = '.';
        }
    }

    private boolean isValid(char[][] path,int n, int rowIdx, int colIdx) {
        //判断列
        for (int i = 0; i < rowIdx; i++) {
            if(path[i][colIdx] == 'Q'){
                return false;
            }
        }

        //45
        for(int i = rowIdx - 1,j = colIdx - 1;i >= 0 && j>=0;i--,j--){
            if(path[i][j] == 'Q'){
                return false;
            }
        }

        //135
        for(int i = rowIdx - 1,j = colIdx + 1;i >= 0 && j < n;i--,j++){
            if(path[i][j] == 'Q'){
                return false;
            }
        }
        return true;
    }

    private List<String> charsToList(char[][] path) {
        List<String> list = new ArrayList<>();
        for (char[] chars : path) {
            StringBuilder sb = new StringBuilder();
            for (char c : chars) {
                sb.append(c);
            }
            list.add(sb.toString());
        }
        return list;
    }


}
